package com.gensdai.leliang.activity;

import android.content.Context;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;

import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.VirtualLayoutManager;
import com.alibaba.android.vlayout.layout.LinearLayoutHelper;
import com.gensdai.leliang.R;
import com.gensdai.leliang.base.BaseActivity;
import com.gensdai.leliang.common.adapter.CommentAdapterRec;
import com.gensdai.leliang.common.bean.CommentInfoBean;
import com.gensdai.leliang.remoteInterface.RetrofitFactory;
import com.gensdai.leliang.retrofitUtils.BaseObserverList;
import com.gensdai.leliang.retrofitUtils.ModelFilteredFactory;
import com.kaopiz.kprogresshud.KProgressHUD;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreater;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreater;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * 评论列表
 * Created by zsxx on 2017/8/17.
 */

public class ActivityCommentList extends BaseActivity {
    public static final String EXTRA_RELATIONID = "EXTRID";
    @BindView(R.id.comment_list_rec)
    RecyclerView commentListRec;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;


    private String relationid = "";
    KProgressHUD hud;

    int pageNum = 0;
    int pageSize = 15;

    @Override
    protected String getTitleStr() {
        return "评论";
    }

    @Override
    protected boolean isShowBackButton() {
        return true;
    }

    @Override
    protected boolean isCustomTitle() {
        return false;
    }

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_comment_list;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        relationid = getIntent().getStringExtra(EXTRA_RELATIONID);
        initRecyclerView(commentListRec);
        /*初始化dialog*/
        hud = KProgressHUD.create(this)
                .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
                .setLabel("正在处理...")
                .setCancellable(true)
                .setAnimationSpeed(1)
                .setDimAmount(0.5f);

        initrefreshlayout();

//        getCommentList(relationid);
    }
    private void initrefreshlayout(){
        refreshLayout.setDefaultRefreshHeaderCreater(new DefaultRefreshHeaderCreater() {
            @Override
            public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout) {
                //指定为经典Header，默认是 贝塞尔雷达Header
                return new ClassicsHeader(context).setSpinnerStyle(SpinnerStyle.Translate);
            }
        });

        refreshLayout.setDefaultRefreshFooterCreater(new DefaultRefreshFooterCreater() {
            @Override
            public RefreshFooter createRefreshFooter(Context context, RefreshLayout layout) {
                //指定为经典Footer，默认是 BallPulseFooter
                return new ClassicsFooter(context).setSpinnerStyle(SpinnerStyle.Translate);
            }
        });

        refreshLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                getCommentList(relationid,true);
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                pageNum = 0;
                getCommentList(relationid,false);
            }
        });

        //设置滚动到最底部是否加载更多
        refreshLayout.setEnableAutoLoadmore(true);
        refreshLayout.setDisableContentWhenRefresh(true);
        refreshLayout.autoRefresh();
    }

    private void getCommentList(String id,final boolean loadMore) {
        Map<String, String> params = new HashMap<>();
        params.put("productRelationId", id);
        params.put("page", pageNum + "");
        params.put("pageNum", pageSize + "");
        ModelFilteredFactory.compose(RetrofitFactory.getInstance().API().GETCOMMENTLIST(params))
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        //开始监听前的处理，一般用于显示dialog什么的
//                        if (hud != null) {
//                            hud.show();
//                        }
                        Log.d("accept", "accept");
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserverList<CommentInfoBean>(this) {
                    @Override
                    public void onRequestEnd() {
                        super.onRequestEnd();
                        if (hud != null && hud.isShowing()) {
                            hud.dismiss();
                        }
                    }

                    @Override
                    public void onHandleSuccess(List<CommentInfoBean> t) {
                        attrRecycler(t,loadMore);
                    }

                    @Override
                    public void onHandleError(int code, String message) {

                    }
                });

    }


    LinearLayoutHelper layoutHelper;
    List<CommentInfoBean> beans;
    CommentAdapterRec adapter;
    private void attrRecycler(List<CommentInfoBean> t,boolean isLoadMore) {

        if(t != null){
            if(t.size() >= pageSize){
                refreshLayout.setEnableLoadmore(true);
                pageNum += 1;
            }else{
                refreshLayout.setEnableLoadmore(false);
            }
            if(layoutHelper == null){
                layoutHelper = new LinearLayoutHelper();
                layoutHelper.setDividerHeight(2);
                layoutHelper.setBgColor(ContextCompat.getColor(this, R.color.bgColor_new));
            }

            if(isLoadMore){
                beans.addAll(t);
                adapter.notifyDataSetChanged();
                delegateAdapter.notifyDataSetChanged();
                refreshLayout.finishLoadmore();
            }else{
                refreshLayout.finishRefresh();
                beans = new ArrayList<>();
                if (adapters != null) {
                    beans = t;
                    adapter = new CommentAdapterRec(this, layoutHelper, beans);
                    adapters.clear();
                    adapters.add(adapter);

                }else{
                    adapters = new LinkedList<>();
                    beans = t;
                    adapter = new CommentAdapterRec(this, layoutHelper, beans);
                    adapters.clear();
                    adapters.add(adapter);
                }

                //初始化完毕后开始适配
                delegateAdapter.setAdapters(adapters);
                delegateAdapter.notifyDataSetChanged();
            }
        }

    }


    DelegateAdapter delegateAdapter;
    List<DelegateAdapter.Adapter> adapters;

    private void initRecyclerView(RecyclerView recyclerView) {
        //创建线性布局
        final VirtualLayoutManager layoutManager = new VirtualLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        // layoutManager.setReverseLayout(true);

        RecyclerView.ItemDecoration itemDecoration = new RecyclerView.ItemDecoration() {
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                int position = ((VirtualLayoutManager.LayoutParams) view.getLayoutParams()).getViewPosition();
                outRect.set(4, 4, 4, 4);
            }
        };

        final RecyclerView.RecycledViewPool viewPool = new RecyclerView.RecycledViewPool();

        recyclerView.setRecycledViewPool(viewPool);

        // recyclerView.addItemDecoration(itemDecoration);
        viewPool.setMaxRecycledViews(0, 20);

        delegateAdapter = new DelegateAdapter(layoutManager, false);

        recyclerView.setAdapter(delegateAdapter);

        adapters = new LinkedList<>();
    }
}
